<template>
    <view class="goods-list-container">
        <z-paging 
            ref="paging"
            class="goods-list"
            :scroll-with-animation="true"
            :default-page-size="queryParams.page_size"
            v-model="goodsList"
            @query="handlerPullRefreshAndMore"
            @scroll="handleScroll"
        >
            <!-- 头部区域开始 -->
            <template #top>
                <TridentFreshGoodsSearch :keyword="queryParams.keyword ? queryParams.keyword : '搜索商品'" btn_txt="首页"/>
                <view class="filter-tab-wrap">
                    <view class="filter-tab-item" @click="selectFilterTabs(index)" v-for="(item, index) in filters" :key="index">
                        <text class="filter-tab-txt" :class="{active: currentIndex == index}">{{item.name}}</text>
                        <text class="icon iconfont icon-shangjiantou active" v-if="currentIndex == index"></text>
                        <text class="icon iconfont icon-xiajiantou1" v-else></text>
                    </view>
                </view>

                <!-- 通过filter.type判断显示哪些筛选条件 -->
                <view class="filter-content" v-if="isShowFilter">
                    <view class="filter-list">

                        <!-- 过滤区域开始 -->
                        <template v-if="filter.type == 'filter'">
                            <view v-for="(item, index) in filter.children" :key="index" class="filter-item" :class="filterValue == item.value ? 'active' : ''" @click="changeFilter(item.name, item.value, filter.type)">
                                <text class="filter-txt">{{ item.name }}</text>
                                <text class="icon iconfont icon-duigou" v-if="filterValue == item.value"></text>
                            </view>
                        </template>
                        <!-- 过滤区域结束 -->


                        <!-- 排序区域开始 -->
                        <template v-else-if="filter.type == 'sort'">
                            <view v-for="(item, index) in filter.children" :key="index" class="filter-item" :class="sortValue == item.value ? 'active' : ''" @click="changeSort(item.name, item.value, filter.type)">
                                <text class="filter-txt">{{ item.name }}</text>
                                <text class="icon iconfont icon-duigou" v-if="sortValue == item.value"></text>
                            </view>
                        </template>
                        <!-- 排序区域结束 -->


                        <!-- 综合筛选区域开始 -->
                        <template v-else-if="filter.type == 'complex_filter'">

                            <!-- 最低价、最高价筛选 -->
                            <view class="price-wrap">
                                <view v-for="(item, index) in filter.children" :key="index" class="item-wrap">
                                    <text class="price-txt">{{ item.name }}</text>
                                    <input class="price-input" v-model="item.value" type="text" :placeholder="'请输入'+item.name">
                                </view>
                            </view>

                            <!-- 品牌筛选 -->
                            <view class="brand-wrap" v-if="searchFilterList.brand_aggs">
                                <view class="title">品牌筛选</view>
                                <view class="content">
                                    <template v-for="(item, index) in searchFilterList.brand_aggs.values" :key="index">
                                        <text class="item ellipsis-1" v-if="item.key != ''" :class="{active: item.key == queryParams.brand_name}" @click="selectBrand(item.key)">{{item.key}}</text>
                                    </template>
                                </view>
                            </view>

                            <!-- 分类筛选 -->
                            <view class="category-wrap" v-if="searchFilterList.category_aggs">
                                <view class="title">分类筛选</view>
                                <view class="content">
                                    <template v-for="(item, index) in searchFilterList.category_aggs.values" :key="index">
                                        <text class="item ellipsis-1" v-if="item.key != ''" :class="{active: item.key == queryParams.category_name}" @click="selectCategory(item.key)">{{item.key}}</text>
                                    </template>
                                </view>
                            </view>

                            <view class="complex-filter-btn">
                                <text class="btn" @click="onReset(filter.children)">重置</text>
                                <text class="btn primary" @click="onConfirm(filter.children)">确定</text>
                            </view>
                        </template>
                        <!-- 综合筛选区域结束 -->
                    </view>
                </view>
            </template>
            <!-- 头部区域结束 -->

            <!-- 商品区域开始 -->
            <view class="goods-wrap">
                <!-- 骨架屏区域 -->
                <view v-if="isShowSkeleton" style="display: flex;flex-wrap: wrap;justify-content: space-between;margin: 0 20rpx;">
                    <uv-skeletons :loading="isShowSkeleton" :skeleton="skeleton" v-for="(item, index) in 6" :key="index"></uv-skeletons>
                </view>

                <view class="content" v-else>
                    <TridentFreshGoodsItem v-for="(item, index) in goodsList" :key="index" :goods="item"/>
                </view>
            </view>
            <!-- 商品区域结束 -->

            <!-- 加载更多提示 -->
            <template #loadingMoreNoMore>
                <view :style=" safeAreaInsets.bottom > 0 ? 'padding-bottom: ' + safeAreaInsets.bottom + 'px': ''" class="no-more" v-if="pageTotal == queryParams.page && pageTotal > 1">我也是有底线的！</view>
            </template>
        </z-paging>

        <!-- 返回顶部 -->
		<TridentFreshBackTop @backTop="backTop" :isShowBackTop="isShowBackTop"/>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, inject, computed } from "vue";
import { onShow } from '@dcloudio/uni-app'
import { reqGetGoodsListAPI, reqSearchFilterAPI } from "@/apis/goods"

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const global:any = inject('global')

// 获取页面参数
const query = defineProps({
    "keyword": {
        type: String,
        default: ''
    },
    "second_cid": {
        type: String,
        default: "0"
    },
    "cid": {
        type: String,
        default: "0"
    }
})

onShow(() => {
    queryParams.keyword = query.keyword
    queryParams.second_cid = query.second_cid
    queryParams.cid = query.cid
})

const isShowFilter = computed(() => {
    return filter.value.type ? true : false
})

// ------------------ 定义骨架变量开始 ----------------------
// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive([
    {
        type: 'custom',
        num: 1,
        style: 'width: 350rpx;height:310rpx;border-top-left-radius: 20rpx;border-top-right-radius: 20rpx;',
    },
    20,
    {
        type: 'line',
        num: 1,
        style: 'width: 350rpx;margin: 1%;height:60rpx;',
    },
    20,
    {
        type: 'flex',
        num: 1,
        style: 'justify-content: space-between;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 150rpx;height: 40rpx',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 100rpx;height: 40rpx',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 60rpx;height: 60rpx;border-radius: 30rpx;',
            }
        ]
    },
    40
])
// ------------------ 定义骨架变量结束 ------------------



// ----------------- 返回顶部功能开始 ------------------
// 定义是否显示返回顶部
const isShowBackTop = ref(false)

// 返回顶部
const backTop = () => {
    paging.value.scrollToTop()
}

// 当滚动触发时，调用事件用于显示、隐藏返回顶部图标
const handleScroll = (e:any) => {
    isShowBackTop.value = e.detail.scrollTop > 300 ? true : false
}
// ----------------- 返回顶部功能结束 ------------------



// 定义过滤数据
const filters = ref([
    {
        name: '全部商品',
        type: 'filter',
        children: [
            {
                name: '全部商品',
                value: 0,
            },
            {
                name: '新款商品',
                value: 1,
            },
            {
                name: '热门商品',
                value: 2,
            }
        ]
    },
    {
        name: '默认排序',
        type: 'sort',
        children: [
            {
                name: '默认排序',
                value: 0,
            },
            {
                name: '价格由低到高',
                value: 1,
            },
            {
                name: '价格由高到低',
                value: 2,
            },
            {
                name: '销售排序',
                value: 3,
            },
            {
                name: '点赞排序',
                value: 4,
            },
            {
                name: '收藏排序',
                value: 5,
            }
        ]
    },
    {
        name: '筛选',
        type: 'complex_filter',
        children: [
            {
                name: '自定最低价',
                field: 'min_price',
                value: '',
            },
            {
                name: '自定最高价',
                field: 'max_price',
                value: '',
            }
        ]
    }
])

const currentIndex = ref(-1)

const filter:any = ref({})

// 选择过滤方式
const selectFilterTabs = (index:any) => {
    paging.value.scrollToTop()

    currentIndex.value = index
    filter.value = filters.value[index]
    if (index == 2) {
        getSearchFilter()
    }
}

// 清除商品列表参数
const clearQueryParams = () => {
    queryParams.brand_id = 0
    queryParams.brand_name = ''
    queryParams.category_name = ''
	queryParams.min_price = ''
	queryParams.max_price = ''
	queryParams.sort_field = 'goods_id'
	queryParams.sort_mode = 'desc'
    queryParams.is_hot = 'all'
    queryParams.is_new = 'all'
	queryParams.page = 1
	goodsList.value = []
}

// ------------------ 商品列表过滤功能开始 ------------------
// 过滤值
const filterValue = ref(0)

const changeFilter = (name:any, value:any, filterType:any) => {
    filterValue.value = value
    currentIndex.value = -1
    filter.value = {}
    // 修改过滤类型
    filters.value.forEach(item => {
        if (item.type == filterType) {
            item.name = name
        }
    })

    clearQueryParams()
    
    if (value == 1) { // 新款商品
        queryParams.is_new = 1
    } else if (value == 2) { // 热门商品
        queryParams.is_hot = 1
    }

	// 当tab切换或搜索时，可以通过paging.value.reload()刷新整个列表
    paging.value.reload()
}
// ------------------ 商品列表筛选功能结束 ------------------



// ------------------ 商品列表排序功能开始 ------------------
// 排序值
const sortValue = ref(0)

const changeSort = async (name:any, value:any, filterType:any) => {
    sortValue.value = value
    currentIndex.value = -1
    filter.value = {}
    // 修改过滤类型
    filters.value.forEach(item => {
        if (item.type == filterType) {
            item.name = name
        }
    })

    if (value == 1) { // 价格由低到高
        queryParams.sort_field = 'price'
        queryParams.sort_mode = 'asc'
    } else if (value == 2) { // 价格由高到低
        queryParams.sort_field = 'price'
        queryParams.sort_mode = 'desc'
    } else if (value == 3) { // 销量排序
        queryParams.sort_field = 'sales_num'
        queryParams.sort_mode = 'desc'
    } else if (value == 4) { // 点赞排序
        queryParams.sort_field = 'like_num'
        queryParams.sort_mode = 'desc'
    } else if (value == 5) { // 收藏排序
        queryParams.sort_field = 'collect_num'
        queryParams.sort_mode = 'desc'
    } else {
        queryParams.sort_field = 'goods_id'
	    queryParams.sort_mode = 'desc'
    }

    queryParams.page = 1
	goodsList.value = []

    // 当tab切换或搜索时，可以通过paging.value.reload()刷新整个列表
    paging.value.reload()
}
// ------------------ 商品列表排序功能结束 ------------------



// ---------------- 商品列表复杂筛选功能开始 ----------------
// 选择商品品牌
const selectBrand = (name:any) => {
    queryParams.brand_name = name
}

// 选择商品分类
const selectCategory = (name:any) => {
    queryParams.category_name = name
}

// 确认
const onConfirm = async (items:any) => {
    // 重置参数
    queryParams.min_price = ''
    queryParams.max_price = ''

    // 循环设置参数
    items.forEach((item:any) => {
        switch (item.field) {
            case 'min_price': // 最低价
                if (item.value != '') {
                    queryParams.min_price = parseInt(item.value) * 100
                }
                break;
            
            case 'max_price': // 最高价
                if (item.value != '') {
                    if (queryParams.min_price == '') {
                        queryParams.min_price = 0
                    }
                    queryParams.max_price = parseInt(item.value) * 100
                }
                break;
        
            default:
                break;
        }
    })

    // 判断价格
    if (queryParams.min_price > queryParams.max_price) {
        uni.showToast({
            icon: 'none',
            title: '最低价不能大于最高价',
        })
        return false
    }

    currentIndex.value = -1
    filter.value = {}

    // 重置商品列表参数
    queryParams.page = 1
	goodsList.value = []
    // 当tab切换或搜索时，可以通过paging.value.reload()刷新整个列表
    paging.value.reload()
}

// 重置
const onReset = (items:any) => {
    items.forEach((item:any) => {
        item.value = ''
    })

    queryParams.min_price = ''
    queryParams.max_price = ''
    queryParams.brand_name = ''
    queryParams.category_name = ''
}
// ---------------- 商品列表复杂筛选功能结束 ----------------



// -----------------下拉刷新 + 加载更多开始 -----------------
const handlerPullRefreshAndMore = (pageNo:any, pageSize:any) => {
    queryParams.page = pageNo
    getGoodsList()
}
// -----------------下拉刷新 + 加载更多结束 -----------------



// -------------------- 商品过滤功能开始 --------------------
// 定义搜索数据
const searchFilterList:any = ref({})
const getSearchFilter = async () => {
    const result:any = await reqSearchFilterAPI({...queryParams, brand_name: '', category_name: '', page_size: 10})
    searchFilterList.value = result.data.search_filters != null ? result.data.search_filters : {}
}
// -------------------- 商品过滤功能结束 --------------------



// ------------------ 获取商品列表功能开始 -------------------
const paging = ref()

// 定义商品列表
const goodsList = ref([])

// 商品数量
const total = ref(0)

// 总页数
const pageTotal = ref(0)

// 请求参数
const queryParams:any = reactive({
	keyword: '',
    top_cid: global.CID,
    second_cid: 0,
	cid: 0,
	brand_id: 0,
    brand_name: '',
    category_name: '',
	min_price: '',
	max_price: '',
	sort_field: 'goods_id',
	sort_mode: 'desc',
    is_hot: 'all',
    is_new: 'all',
	page: 1,
	page_size: 20
})

// 请求商品数据
const getGoodsList = async () => {
    // 显示骨架
    if (queryParams.page == 1) {
        isShowSkeleton.value = true
    }

	// 请求数据
	const result:any = await reqGetGoodsListAPI(queryParams)
	let goodsItems = result.data.goods != null ? result.data.goods : []
    total.value = result.data.total
    pageTotal.value = result.data.page_total
    goodsItems.forEach((item:any) => {
        item.name = item.goods_name
        item.original_price = item.market_price
        item.image_url = item.cover_url
        item.desc = item.descibe.replace(/<.*?>/ig, "")
    })
    paging.value.complete(goodsItems);

    // 隐藏骨架
    isShowSkeleton.value = false
}
// ------------------ 获取商品列表功能结束 -------------------
</script>

<style scoped lang="scss">
.goods-list-container {
    .goods-list {
        // 过滤tab
        .filter-tab-wrap {
            background-color: #fff;
            margin-top: 90rpx;
            border-bottom: 2rpx solid #ccc;
            
            display: flex;


            height: 80rpx;
            line-height: 80rpx;
            text-align: center;
            z-index: 100;

            .filter-tab-item {
                flex: 1;

                .filter-tab-txt {
                    margin-right: 10rpx;
                }
                .icon {
                    font-size: 24rpx;
                    color: #ccc;
                }

                .active {
                    color: #008000;
                }
            }
        }

        // 过滤内容
        .filter-content {
            background-color: rgba(0, 0, 0, 0.7);
            height: 100vh;

            transition: all 0.7s;

            position: relative;
            .filter-list {
                background-color: #fff;
                .filter-item {
                    height: 80rpx;
                    line-height: 80rpx;
                    margin: 0 20rpx;
                    border-bottom: 2rpx dashed #ccc;

                    display: flex;
                    justify-content: space-between;
                    .filter-txt {
                        font-size: 24rpx;
                    }
                    &:last-child {
                        border-bottom: none;
                    }
                }

                // 最低价、最高价筛选
                .price-wrap {
                    margin: 0 20rpx;
                    padding: 20rpx 0;

                    .item-wrap {
                        display: flex;
                        align-items: center;
                        padding-bottom: 20rpx;

                        .price-txt {
                            font-size: 24rpx;
                            width: 120rpx;
                            margin-right: 20rpx;
                        }
                        .price-input {
                            flex: 1;
                            font-size: 24rpx;
                            border: 2rpx solid #ccc;
                            padding: 0 10rpx;
                            height: 60rpx;
                        }
                    }
                }

                // 品牌筛选
                .brand-wrap {
                    padding: 0 20rpx;
                    .title {
                        text-align: center;
                        color: #008000;
                        font-size: 30rpx;
                        font-weight: bold;
                    }
                    .content {
                        margin: 20rpx 0;
                        display: flex;
                        flex-wrap: wrap;
                        .item {
                            text-align: center;
                            border: 2rpx solid #ccc;
                            padding: 4rpx 5rpx;
                            margin-right: 20rpx;
                            margin-bottom: 20rpx;
                            border-radius: 2rpx;
                            width: 29%;
                            &:nth-child(3n) {
                                margin-right: 0;
                            }
                        }
                        .active {
                            color: #fff;
                            background-color: #008000;
                        }
                    }
                }

                // 分类筛选
                .category-wrap {
                    padding: 0 20rpx;
                    .title {
                        text-align: center;
                        color: #008000;
                        font-size: 30rpx;
                        font-weight: bold;
                    }
                    .content {
                        margin: 20rpx 0;
                        display: flex;
                        flex-wrap: wrap;
                        .item {
                            text-align: center;
                            border: 2rpx solid #ccc;
                            padding: 4rpx 10rpx;
                            margin-right: 20rpx;
                            margin-bottom: 20rpx;
                            border-radius: 2rpx;
                            width: 28%;
                            &:nth-child(3n) {
                                margin-right: 0;
                            }
                        }
                        .active {
                            color: #fff;
                            background-color: #008000;
                        }
                    }
                }

                .complex-filter-btn {
                    display: flex;
                    justify-content: space-evenly;

                    padding: 30rpx 0 20rpx 0;
                    border-top: 2rpx solid #ccc;
                    .btn {
                        width: 30%;
                        text-align: center;
                        padding: 10rpx 0;
                        background-color: #ccc;
                        color: #fff;
                        border-radius: 8rpx;
                    }
                    .primary {
                        background-color: #008000;
                    }
                }

                .active {
                    color: #008000;
                }
            }
        }

        .goods-wrap {
            .content {
                display: flex;
                flex-wrap: wrap;
                padding: 0 10rpx 20rpx 10rpx;
            }
        }

        // 没有更多区域
        .no-more {
            text-align: center;
            padding-bottom: 20rpx;
            color: #ccc;
            &::before {
                content: '-------------';
                margin-right: 10rpx;
            }
            &::after {
                content: '-------------';
                margin-right: 10rpx;
            }
        }
    }
}
</style>